package net.bither.util;

import android.graphics.Bitmap;

import java.io.ByteArrayOutputStream;


/**
 * JNI图片压缩工具类 采用哈夫曼算法
 */
public class NativeUtil {

    private static final String TAG = "NativeUtil";

    /**
     * 两个核心类库
     */
    static {
        System.loadLibrary("jpegbither");
        System.loadLibrary("bitherjni");
    }

    /**
     * 将Bitmap压缩后并保存到sd卡
     *
     * @param bmp       Bitmap对象
     * @param outFile   输出路径
     * @param applySize 期望压缩后的大小 单位kb
     * @param optimize  是否采用哈弗曼表数据计算 品质相差5-10倍
     */
    public static void compressBitmap(Bitmap bmp, String outFile, int applySize, boolean optimize) {
        int compressRatio = compressRatio(bmp, applySize);
        saveBitmap(bmp, compressRatio, outFile, optimize);
    }

    /**
     * 计算压缩比
     *
     * @param bmp       Bitmap对象
     * @param applySize 期望大小，单位kb
     */
    public static int compressRatio(Bitmap bmp, int applySize) {
        int compressRatio = 100;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, compressRatio, bos);
            while (bos.toByteArray().length / 1024 > applySize) {
                bos.reset();
                compressRatio -= 5;
                bmp.compress(Bitmap.CompressFormat.JPEG, compressRatio, bos);
            }
            return compressRatio;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return compressRatio;
    }

    /**
     * @param bmp      Bitmap对象
     * @param quality  压缩比
     * @param outPath  输出路径
     * @param optimize 是否使用哈夫曼算法
     */
    private static void saveBitmap(Bitmap bmp, int quality, String outPath, boolean optimize) {
        compressBitmap(bmp, bmp.getWidth(), bmp.getHeight(), quality, outPath.getBytes(), optimize);
    }

    /**
     * 执行哈夫曼算法压缩
     *
     * @param bmp         Bitmap对象
     * @param width       bmp的宽度
     * @param height      bmp的高度
     * @param compress    压缩比
     * @param outFileByte 输出路径
     * @param optimize    是否使用哈夫曼算法
     */
    private static native String compressBitmap(Bitmap bmp, int width, int height, int compress, byte[] outFileByte, boolean optimize);

}